import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateRoleDto } from './dto/create-role.dto'
import { UpdateRoleDto } from './dto/update-role.dto'
import { RoleEntity } from './entities/role.entity'

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(RoleEntity)
    private readonly roleRepository: Repository<RoleEntity>,
  ) {}

  async create(dto: CreateRoleDto) {
    const result = await this.roleRepository.create(dto)
    await this.roleRepository.save(result)

    return result
  }

  findAll() {
    return this.roleRepository.find({ relations: ['menus'] })
  }

  // 详情
  findOne(id) {
    return this.roleRepository.findOne({ where: { id }, relations: ['menus'], order: { order: 'ASC' } })
  }

  // 修改
  async update(id, dto: UpdateRoleDto) {
    const old = await this.findOne(id)
    const vo = await this.roleRepository.merge(old, dto)

    return this.roleRepository.save(vo)
  }

  // 删除
  async remove(id) {
    const result = await this.roleRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
